package com.netsdk.lht2.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class LogUtil {
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    String prefix ;
    LogFileInfo currentLogFileInfo;

    public LogUtil(String prefix) throws IOException {
        this.prefix = prefix;
        currentLogFileInfo = createLogFileInfo();
    }

    public void log(String data) throws Exception {
        FileOutputStream logWrite = getLogWrite();
        logWrite.write(data.getBytes());
//        logWrite.write("\n".getBytes());
    }

    private FileOutputStream getLogWrite() throws Exception {
        LogFileInfo logFileInfo = getCurrentLogFileInfo();
        return logFileInfo.fileOutputStream;
    }


    static class LogFileInfo {
        String time;
        File file;
        FileOutputStream fileOutputStream;
        public void close(){
            try {
                fileOutputStream.close();
            }catch (Exception e){}
        }
    }
    private LogFileInfo createLogFileInfo() throws IOException {
        LogFileInfo logFileInfo = new LogFileInfo();
        logFileInfo.time  = getCurrentTimeString();
        File file = new File("./log/"+ prefix + "-" + logFileInfo.time+ ".txt");
        if (!file.exists()){
            file.createNewFile();
            logFileInfo.file = file;
        }
        logFileInfo.fileOutputStream = new FileOutputStream(file,true);
        return logFileInfo;
    }

    private synchronized LogFileInfo getCurrentLogFileInfo() throws IOException {
        LogFileInfo logFileInfo = currentLogFileInfo;
        String time = logFileInfo.time;
        String currentTimeString = getCurrentTimeString();
        if (!currentTimeString.equals(time)){
            // 关闭文件输出
            logFileInfo.close();
            logFileInfo = createLogFileInfo();
            currentLogFileInfo = logFileInfo;
        }
        return currentLogFileInfo;
    }

    private String getCurrentTimeString(){
        LocalDateTime now = LocalDateTime.now();
        return now.format(dateTimeFormatter);
    }

}
